package com.mspbots.core.wise.controller;

import com.mspbots.core.AbstractBaseController;
import com.mspbots.core.wise.model.TenantConfiguration;
import com.mspbots.core.wise.service.TenantConfigurationService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.Callable;

@RestController
@RequestMapping("{tenant}/configuration")
@RequiredArgsConstructor
public class TenantConfigurationController extends AbstractBaseController<TenantConfiguration, TenantConfigurationService> {

    private final RabbitMessagingTemplate messagingTemplate;

    @GetMapping("/tenantId/{tenantId}")
    public Callable getAllByTenantId(@PathVariable("tenantId") long tenantId) {
        return () -> service.selectAllByTenantId(tenantId);
    }

    @GetMapping(path = "keyword")
    public Callable selectByKey(TenantConfiguration tenantConfiguration) {
        return () -> service.selectByKeyword(tenantConfiguration.getTenantId(), tenantConfiguration.getKeyword());
    }

    @GetMapping(path = "keyword/{keyword}")
    public Callable<List<TenantConfiguration>> selectListByKeyword(@PathVariable String keyword) {
        return () -> service.selectListByKeyword(keyword);
    }


    @PostMapping("add-batch")
    public Callable addAll(@RequestBody List<TenantConfiguration> configurations) {
        return () -> this.service.saveBatch(configurations);
    }


    @PostMapping("save-batch")
    public Callable batchSave(@RequestBody List<TenantConfiguration> configurations) {
        return () -> this.service.batchSave(configurations);
    }

    @Override
    @PostMapping
    public Callable insert(@RequestBody TenantConfiguration entity) {
        return () -> {
            service.saveOrUpdate(entity);
            if ("isShowMRR".equalsIgnoreCase(entity.getKeyword())) {
                this.messagingTemplate.convertAndSend("next-ticket.redis.configuration", "", entity);
            }
            return entity;
        };
    }

    @Override
    @PutMapping(path = "/{id}")
    public Callable update(@RequestBody TenantConfiguration entity) {
        return () -> {
            service.updateById(entity);
            if ("isShowMRR".equalsIgnoreCase(entity.getKeyword())) {
                this.messagingTemplate.convertAndSend("next-ticket.redis.configuration", "", entity);
            }
            return entity;
        };
    }

}
